#include "bsp_stm32flash.h"
#include "bsp_exti.h"
#include "bsp_A_phase_zero_point_tim.h"
#include "bsp_B_phase_zero_point_tim.h"
#include "bsp_C_phase_zero_point_tim.h"
#include "bsp_usart.h"

static uint16_t A_Phase_Buff = 0, B_Phase_Buff = 0, C_Phase_Buff = 0;

/**
  * @brief  读取参数
  * @param  无
  * @retval 无
  */
void Read_Param(void)
{
    A_Phase_Rising_Edge_To_Zero_Point = *((volatile uint16_t *)(A_PHASE_PARAM_ADDR));
    B_Phase_Rising_Edge_To_Zero_Point = *((volatile uint16_t *)(B_PHASE_PARAM_ADDR));
    C_Phase_Rising_Edge_To_Zero_Point = *((volatile uint16_t *)(C_PHASE_PARAM_ADDR));
    if (A_Phase_Rising_Edge_To_Zero_Point == 0xFFFF)
    {
        A_Phase_Rising_Edge_To_Zero_Point = A_PHASE_RISING_EDGE_TO_ZERO_POINT;
    }
    if (B_Phase_Rising_Edge_To_Zero_Point == 0xFFFF)
    {
        B_Phase_Rising_Edge_To_Zero_Point = B_PHASE_RISING_EDGE_TO_ZERO_POINT;
    }
    if (C_Phase_Rising_Edge_To_Zero_Point == 0xFFFF)
    {
        C_Phase_Rising_Edge_To_Zero_Point = C_PHASE_RISING_EDGE_TO_ZERO_POINT;
    }
    A_Phase_Buff=A_Phase_Rising_Edge_To_Zero_Point;
    B_Phase_Buff=B_Phase_Rising_Edge_To_Zero_Point;
    C_Phase_Buff=C_Phase_Rising_Edge_To_Zero_Point;
    printf("\r\nRead_Param\r\n");
    printf("A_Phase_Para:%d\r\n", A_Phase_Rising_Edge_To_Zero_Point);
    printf("B_Phase_Para:%d\r\n", B_Phase_Rising_Edge_To_Zero_Point);
    printf("C_Phase_Para:%d\r\n", C_Phase_Rising_Edge_To_Zero_Point);
}

/**
  * @brief  存储参数
  * @param  无
  * @retval 无
  */
void Save_Param(void)
{
    if ((A_Phase_Buff != A_Phase_Rising_Edge_To_Zero_Point) || (B_Phase_Buff != B_Phase_Rising_Edge_To_Zero_Point) || (C_Phase_Buff != C_Phase_Rising_Edge_To_Zero_Point))
    {
        A_Phase_Buff = A_Phase_Rising_Edge_To_Zero_Point;
        B_Phase_Buff = B_Phase_Rising_Edge_To_Zero_Point;
        C_Phase_Buff = C_Phase_Rising_Edge_To_Zero_Point;
        FLASH_Unlock();
        /* Clear pending flags (if any) */
        FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
        FLASH_ErasePage(LAST_PAGE_START_ADDR);

        FLASH_ProgramHalfWord(A_PHASE_PARAM_ADDR, A_Phase_Rising_Edge_To_Zero_Point);
        FLASH_ProgramHalfWord(B_PHASE_PARAM_ADDR, B_Phase_Rising_Edge_To_Zero_Point);
        FLASH_ProgramHalfWord(C_PHASE_PARAM_ADDR, C_Phase_Rising_Edge_To_Zero_Point);
        FLASH_Lock();
        printf("\r\nSave_Param\r\n");
    }

    printf("\r\nA_Phase_Para:%d\r\n", A_Phase_Rising_Edge_To_Zero_Point);
    printf("B_Phase_Para:%d\r\n", B_Phase_Rising_Edge_To_Zero_Point);
    printf("C_Phase_Para:%d\r\n", C_Phase_Rising_Edge_To_Zero_Point);
}
